var express = require('express');
var router = express.Router();
const bcrypt = require('bcryptjs')
var { roleModel, routerMoudel, userModel, orderModel, shopCartModel, shopModel } = require('../model/model')
const _ = require('lodash');
// const  eventsource  = require("eventsource")
/* GET users listing. */

const jwt = require("jsonwebtoken")

const saltRounds = 10; // 定义盐轮数，越大越安全但计算代价也更高
//注册
router.post('/register', async (req, res) => {
  let { username, password } = req.body
  // 加密密码
  const encrypt = await bcrypt.hash(password, saltRounds)
  await loginModel.create({ username: username, password: encrypt })
  res.send({
    code: 200,
    msg: "注册成功"
  })
})
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});
router.get('/getRouter', async (req, res) => {
  let data = await routerMoudel.find().lean()

  let routerobj = {}
  data.forEach((item) => {
    routerobj[item._id] = item
  })
  let routerlist = [];
  data.forEach((item) => {
    if (!item['MenuId']) {
      routerlist.push(item)
    } else {
      if (!routerobj[item['MenuId']]) { // 添加判断语句
        return
      }
      if (!routerobj[item['MenuId']]['children']) {
        routerobj[item['MenuId']]['children'] = []
      }
      routerobj[item['MenuId']]['children'].push(item)
    }
  })
  console.log(routerlist);
  res.send({
    code: 200,
    msg: '数据渲染成功',
    routerlist
  })
})
//登录
router.post('/login', async (req, res) => {
  let { username, password } = req.body
  let user = await userModel.findOne({ username: username })
  if (user) {
    const isPasswordValid = bcrypt.compareSync(password, user.password);
    if (true) {
      let token=jwt.sign({
        username:user.username,
      },"dgj",{expiresIn:60*60*24*7})
      let mid=await roleModel.findOne({_id:user.rid})
      let menu = await routerMoudel.find().lean()
      //根据menuid中的数据 查找这个id对应的权限信息
      let menulist = []
      mid.mid.forEach((id) => {
        menu.forEach((item) => {
          if (String(id) === String(item._id)) {
            menulist.push(item)
          }
        })
      })
      let cateObj = {}
      menulist.forEach(item => {
        cateObj[item._id] = item
      })
      let data = []
      menulist.forEach(item => {
        if (!item['MenuId']) {
          data.push(item)
        } else {
          if (!cateObj[item['MenuId']]) { // 添加判断语句
            return
          }
          if (!cateObj[item['MenuId']]['children']) {
            cateObj[item['MenuId']]['children'] = []
          }
          cateObj[item['MenuId']]['children'].push(item)
        }
      
      })
      res.send({
        code: 200,
        msg: "登陆成功",
       routerList :data,
        token
      })
    } else {
      res.send({
        code: 201,
        msg: "密码错误"
      })
    }
  } else {
    res.send({
      code: 203,
      msg: "用户名错误"
    })
  }
 

})




/**
 * 处理服务器发送事件（Server-Sent Events）的路由。
 * 当客户端请求此路由时，服务器将持续向客户端发送数据。
 * 
 * @param {object} req - 请求对象，包含客户端发起的请求信息。
 * @param {object} res - 响应对象，用于向客户端发送响应。
 */
router.get('/sse', async (req, res) => {
  // 设置响应头，以支持服务器发送事件，禁用缓存并保持连接 alive。
  res.set({
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });

  // 立即发送响应头，避免延迟。
  res.flushHeaders();
  // 异步查询用户模型的所有数据。

  let lastState = null
  setInterval(async () => {
    let lst = await userModel.find()
    if (!_.isEqual(lastState, lst)) { // 使用lodash的isEqual方法进行深度比较
      lastState = lst; // 更新最新状态
      res.write(`data: ${JSON.stringify(lastState)}\n\n`);
    }
  }, 1000);
});
module.exports = router;
